using UnityEngine;
using System.Collections.Generic;
using UnityEditor;
#if UNITY_EDITOR
using UnityEditor;
#endif

public class ImageCacheManager
{
    private class CacheItem
    {
        public Texture2D texture;
        public int refCount;
        public float lastAccessTime;
    }

    private static Dictionary<string, CacheItem> cache = new Dictionary<string, CacheItem>();

    // 如果某个图片超过 30 秒未被使用，则自动释放
    private static float releaseThreshold = 30f;
    private static bool autoReleaseRunning = false;

    /// <summary>
    /// 通过图片路径加载图片，并进行缓存。如果图片已被缓存，则增加引用计数。
    /// </summary>
    public static Texture2D LoadImage(string path)
    {
        #if UNITY_EDITOR
        if (string.IsNullOrEmpty(path))
            return null;

        if (cache.TryGetValue(path, out CacheItem item))
        {
            item.refCount++;
            item.lastAccessTime = Time.realtimeSinceStartup;
            return item.texture;
        }
        else
        {
            Texture2D tex = null;
            // 尝试加载为 Sprite
            Sprite sprite = AssetDatabase.LoadAssetAtPath<Sprite>(path);
            if (sprite != null)
            {
                tex = GetSlicedTexture(sprite);
            }
            else
            {
                // 否则直接加载 Texture2D
                tex = AssetDatabase.LoadAssetAtPath<Texture2D>(path);
            }

            if (tex != null)
            {
                CacheItem newItem = new CacheItem
                {
                    texture = tex,
                    refCount = 1,
                    lastAccessTime = Time.realtimeSinceStartup
                };
                cache.Add(path, newItem);
            }

            return tex;
        }
        #endif
        return null;
    }

    /// <summary>
    /// 从切图后的 Sprite 中提取切图区域生成新的纹理
    /// </summary>
    private static Texture2D GetSlicedTexture(Sprite sprite)
    {
        if (sprite == null)
            return null;

        Rect rect = sprite.rect; // 以像素为单位的切图区域
        Texture2D sourceTexture = sprite.texture;
        Texture2D newTex = new Texture2D((int)rect.width, (int)rect.height, sourceTexture.format, false);
        newTex.SetPixels(sourceTexture.GetPixels((int)rect.x, (int)rect.y, (int)rect.width, (int)rect.height));
        newTex.Apply();
        return newTex;
    }

    /// <summary>
    /// 释放对指定图片路径的引用计数。引用计数为 0 时会在自动检测中释放缓存。
    /// </summary>
    public static void ReleaseImage(string path)
    {
        if (cache.TryGetValue(path, out CacheItem item))
        {
            item.refCount = Mathf.Max(0, item.refCount - 1);
            if (item.refCount <= 0)
            {
                item.lastAccessTime = Time.realtimeSinceStartup;
            }
        }
    }

}